import React, { useEffect, useState } from "react";
import styled from "styled-components";
import { Buffer } from "buffer";
import loader from "@/assets/loader.gif";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/utils/useToast"
import { setAvatar, uploadSingleFile } from "@/apis/common";

// 1. 首先获取所有头像
export default function SetAvatar(){
    const navigator = useNavigate();
    const toast = useToast();
    const [avatars, setAvatars] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [selectedAvatar, setSelectedAvatar] = useState(-1);

    const setProfilePicture = async () => {
      if (selectedAvatar === undefined) {
        toast("Please select an avatar first", "error");
        return;
      }
      // 获取要设置的头像
      const image = avatars[selectedAvatar];
      const [success, data] = await uploadSingleFile({file: image, type: 'svg'})
      if (success) {
        const { url } = data
        // 更新头像
        const [avatarSuccess, userData] = await setAvatar({url})
        if (avatarSuccess) {
          localStorage.setItem(import.meta.env.VITE_USER_KEY, JSON.stringify(userData));
          toast.success("Avatar set successfully");
          navigator("/");
        }
      }

    }

    useEffect(() => {
      const images = []
      async function fetchImages (){
        for(let i = 0; i < 4; i++){
          const res = await fetch(`https://api.multiavatar.com/${Math.floor(Math.random() * 1000)}`)
          const buffer = await res.arrayBuffer()
          const base64 = Buffer.from(buffer).toString('base64')
          images.push(`data:image/svg+xml;base64,${base64}`)
        }
        setAvatars(images)
        setIsLoading(false)
        console.log(images)
      }
      fetchImages()
    }, [])

    return (
        <>
        {isLoading ? (
          <Container>
            <img src={loader} alt="loader" className="loader" />
          </Container>
        ) : (
          <Container>
            <div className="title-container">
              <h1>Pick an Avatar as your profile picture</h1>
            </div>
            <div className="avatars">
              {avatars.map((avatar, index) => {
                return (
                  <div
                    className={`avatar ${
                      selectedAvatar === index ? "selected" : ""
                    }`}
                    key={avatar}
                    onClick={() => setSelectedAvatar(index)}
                  >
                    <img
                      src={avatar}
                      alt="avatar"
                    />
                  </div>
                );
              })}
            </div>
            <button onClick={setProfilePicture} className="submit-btn">
              Set as Profile Picture
            </button>
          </Container>
        )}
      </>
    )
}


const Container = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 3rem;
  background-color: #131324;
  height: 100vh;
  width: 100vw;

  .loader {
    max-inline-size: 100%;
  }

  .title-container {
    h1 {
      color: white;
    }
  }
  .avatars {
    display: flex;
    gap: 2rem;

    .avatar {
      border: 0.4rem solid transparent;
      padding: 0.4rem;
      border-radius: 5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: 0.5s ease-in-out;
      img {
        height: 6rem;
        transition: 0.5s ease-in-out;
      }
    }
    .selected {
      border: 0.4rem solid #4e0eff;
    }
  }
  .submit-btn {
    background-color: #4e0eff;
    color: white;
    padding: 1rem 2rem;
    border: none;
    font-weight: bold;
    cursor: pointer;
    border-radius: 0.4rem;
    font-size: 1rem;
    text-transform: uppercase;
    &:hover {
      background-color: #4e0eff;
    }
  }
`;
